// 主服务入口，负责路由分发和调用业务模块
const http = require('http')
const url = require('url')
const path = require('path')
const { logMessage, sendJson, parseBody } = require('./src/utils')
const { wxConfig, qrCodeMap, sampleData, wxLogin, QRCode, uuidv4 } = require('./src/qrcodeService')

// =====================
// 日志功能：每次请求时输出关键信息
// =====================
// 静态资源服务（public目录）
function serveStatic(req, res) {
  const parsedUrl = url.parse(req.url)
  let pathname = `public${parsedUrl.pathname}`
  if (pathname.endsWith('/')) pathname += 'index.html'
  const ext = path.extname(pathname)
  const map = {
    '.ico': 'image/x-icon',
    '.html': 'text/html',
    '.js': 'text/javascript',
    '.json': 'application/json',
    '.css': 'text/css',
    '.png': 'image/png',
    '.jpg': 'image/jpeg',
    '.gif': 'image/gif',
    '.svg': 'image/svg+xml'
  }
  require('fs').exists(pathname, function (exist) {
    if (!exist) {
      res.writeHead(404, { 'Content-Type': 'text/plain' })
      res.end('404 Not Found')
      return
    }
    require('fs').readFile(pathname, function (err, data) {
      if (err) {
        res.writeHead(500, { 'Content-Type': 'text/plain' })
        res.end('500 Internal Server Error')
      } else {
        res.writeHead(200, { 'Content-Type': map[ext] || 'application/octet-stream' })
        res.end(data)
      }
    })
  })
}

// 创建HTTP服务器，处理所有API和静态资源请求
const server = http.createServer(async (req, res) => {
  const parsedUrl = url.parse(req.url, true);
  // 判断是否为二维码状态查询接口
  const isQrcodeStatusApi = /^\/api\/qrcode\/[\w-]+\/status$/.test(req.url);

  // 只在非二维码状态查询接口时输出请求日志
  if (!isQrcodeStatusApi) {
    console.log(`[${new Date().toLocaleString()}] ${req.method} ${req.url}`);
    if (req.method === 'POST' || req.method === 'PUT') {
      let body = '';
      req.on('data', chunk => { body += chunk; });
      req.on('end', () => {
        if (body) {
          try {
            const json = JSON.parse(body);
            console.log('Body:', json);
          } catch (e) {
            console.log('Body:', body);
          }
        }
      });
    }
    if (Object.keys(parsedUrl.query).length > 0) {
      console.log('Query:', parsedUrl.query);
    }
  }
  const method = req.method

  // 处理CORS预检请求
  if (method === 'OPTIONS') {
    res.writeHead(204, {
      'Access-Control-Allow-Origin': '*',
      'Access-Control-Allow-Methods': 'GET,POST,OPTIONS',
      'Access-Control-Allow-Headers': 'Content-Type'
    })
    res.end()
    return
  }

  // 静态资源请求
  if (req.url.startsWith('/static') || req.url.startsWith('/favicon.ico') || req.url.startsWith('/index.html')) {
    serveStatic(req, res)
    return
  }

  // 生成二维码API
  if (method === 'GET' && parsedUrl.pathname === '/api/qrcode') {
    try {
      const qrcodeId = uuidv4()
      const qrcodeData = {
        id: qrcodeId,
        status: 'pending',
        createdAt: new Date(),
        openid: null,
        userInfo: null
      }
      qrCodeMap.set(qrcodeId, qrcodeData)
      const qrcodeContent = JSON.stringify({ qrcodeId })
      const qrcodeImage = await QRCode.toDataURL(qrcodeContent)
      setTimeout(() => {
        if (qrCodeMap.has(qrcodeId)) {
          // logMessage('二维码过期自动删除', { qrcodeId })
          qrCodeMap.delete(qrcodeId)
        }
      }, 5 * 60 * 1000)
      // logMessage('生成新的二维码', { qrcodeId })
      sendJson(res, { qrcodeId, qrcodeImage })
    } catch (error) {
      // logMessage('生成二维码错误', { error: error.message })
      sendJson(res, { error: '生成二维码失败' }, 500)
    }
    return
  }

  // 小程序扫码回调API
  if (method === 'POST' && parsedUrl.pathname === '/api/scan') {
    try {
      const body = await parseBody(req)
      const { qrcodeId, code, userInfo } = body
      if (!qrcodeId || !code) {
        sendJson(res, { error: '参数不完整' }, 400)
        return
      }
      const qrcodeData = qrCodeMap.get(qrcodeId)
      if (!qrcodeData) {
        sendJson(res, { error: '二维码不存在或已过期' }, 404)
        return
      }
      // 新增：只允许一个人扫码
      if (qrcodeData.status === 'scanned' || qrcodeData.status === 'confirmed') {
        sendJson(res, { error: '二维码已被使用' }, 400)
        return
      }
      const now = new Date()
      const createdTime = new Date(qrcodeData.createdAt)
      const diffMinutes = (now - createdTime) / (1000 * 60)
      if (diffMinutes >= 5) {
        qrCodeMap.delete(qrcodeId)
        sendJson(res, { error: '二维码已过期', expired: true }, 400)
        return
      }
      const wxLoginResult = await wxLogin(code, logMessage)
      qrcodeData.status = 'scanned'
      qrcodeData.openid = wxLoginResult.openid
      qrcodeData.userInfo = userInfo
      qrCodeMap.set(qrcodeId, qrcodeData)
      sendJson(res, { success: true })
    } catch (error) {
      sendJson(res, { error: '处理扫码失败' }, 500)
    }
    return
  }

  // 小程序确认登录API
  if (method === 'POST' && parsedUrl.pathname === '/api/scan/confirm') {
    try {
      const body = await parseBody(req)
      const { qrcodeId, userInfo } = body
      // logMessage('收到小程序确认登录请求', { qrcodeId, userInfo })
      if (!qrcodeId) {
        // logMessage('确认登录参数不完整', { qrcodeId })
        sendJson(res, { success: false, message: '参数不完整' }, 400)
        return
      }
      const qrcodeData = qrCodeMap.get(qrcodeId)
      if (!qrcodeData) {
        // logMessage('二维码不存在或已过期', { qrcodeId })
        sendJson(res, { success: false, message: '二维码不存在或已过期' })
        return
      }
      const now = new Date()
      const createdTime = new Date(qrcodeData.createdAt)
      const diffMinutes = (now - createdTime) / (1000 * 60)
      if (diffMinutes >= 5) {
        // logMessage('二维码已过期', { qrcodeId, createdAt: createdTime, now, diffMinutes })
        qrCodeMap.delete(qrcodeId)
        sendJson(res, { success: false, message: '二维码已过期', expired: true })
        return
      }
      qrcodeData.status = 'confirmed'
      qrcodeData.userInfo = userInfo
      qrCodeMap.set(qrcodeId, qrcodeData)
      const token = uuidv4()
      // logMessage('生成登录令牌', { qrcodeId, token })
      setTimeout(() => {
        if (qrCodeMap.has(qrcodeId)) {
          qrCodeMap.delete(qrcodeId)
          // logMessage('已确认的二维码被删除', { qrcodeId })
        }
      }, 10 * 1000)
      sendJson(res, { success: true, message: '登录成功', token, userInfo: qrcodeData.userInfo })
    } catch (error) {
      // logMessage('确认登录错误', { error: error.message })
      sendJson(res, { success: false, message: '处理确认登录失败' })
    }
    return
  }

  // 查询二维码状态API
  if (method === 'GET' && /^\/api\/qrcode\/.+\/status$/.test(parsedUrl.pathname)) {
    const id = parsedUrl.pathname.split('/')[3]
    // logMessage('查询二维码状态', { qrcodeId: id })
    const qrcodeData = qrCodeMap.get(id)
    if (!qrcodeData) {
      // logMessage('二维码不存在或已过期', { qrcodeId: id })
      sendJson(res, { error: '二维码不存在或已过期' }, 404)
      return
    }
    const now = new Date()
    const createdTime = new Date(qrcodeData.createdAt)
    const diffMinutes = (now - createdTime) / (1000 * 60)
    if (diffMinutes >= 5) {
      // logMessage('二维码已过期', { qrcodeId: id, createdAt: createdTime, now, diffMinutes })
      qrCodeMap.delete(id)
      sendJson(res, { error: '二维码已过期', expired: true }, 400)
      return
    }
    // logMessage('返回二维码状态', { qrcodeId: id, status: qrcodeData.status })
    sendJson(res, { status: qrcodeData.status })
    return
  }

  // 获取数据表数据API
  if (method === 'GET' && parsedUrl.pathname === '/api/data') {
    try {
      // logMessage('请求获取数据表数据')
      const sortedData = [...sampleData].sort((a, b) => new Date(b.date) - new Date(a.date))
      // logMessage('返回数据表数据', { count: sortedData.length })
      sendJson(res, sortedData)
    } catch (error) {
      // logMessage('获取数据错误', { error: error.message })
      sendJson(res, { error: '获取数据失败' }, 500)
    }
    return
  }

  // 查看所有二维码状态（调试用）
  if (method === 'GET' && parsedUrl.pathname === '/api/debug/qrcodes') {
    // logMessage('请求查看所有二维码状态')
    const qrcodes = []
    qrCodeMap.forEach((value, key) => {
      const now = new Date()
      const createdTime = new Date(value.createdAt)
      const diffMinutes = (now - createdTime) / (1000 * 60)
      const remainingMinutes = Math.max(0, 5 - diffMinutes).toFixed(2)
      qrcodes.push({
        id: key,
        status: value.status,
        createdAt: value.createdAt,
        remainingMinutes,
        expired: diffMinutes >= 5,
        openid: value.openid ? value.openid.substring(0, 8) + '...' : null
      })
    })
    sendJson(res, { qrcodes })
    return
  }

  // 404处理
  res.writeHead(404, { 'Content-Type': 'application/json' })
  res.end(JSON.stringify({ error: 'Not found' }))
})

// 定时清理过期二维码（每分钟执行一次）
setInterval(() => {
  const now = new Date()
  let expiredCount = 0
  qrCodeMap.forEach((value, key) => {
    const createdTime = new Date(value.createdAt)
    const diffMinutes = (now - createdTime) / (1000 * 60)
    if (diffMinutes >= 5) {
      qrCodeMap.delete(key)
      expiredCount++
    }
  })
  if (expiredCount > 0) {
    // logMessage('定时清理过期二维码', { expiredCount })
  }
}, 60 * 1000)

// 启动HTTP服务器
const PORT = process.env.PORT || 3000
server.listen(PORT, () => {
  console.log(`HTTP服务器已启动，访问 http://localhost:${PORT}`)
  // logMessage('服务器启动', { port: PORT, protocol: 'HTTP' })
}) 